#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <network_manager.h>
#include <config.h>

static int serverInit(void);
static int serverExit(void);

static T_networkOpr server = 
{
	.name			= "server",
	.networkInit 	= serverInit,
	.networkExit 	= serverExit,
	.networkConnect = NULL,
	.networkSend 	= NULL,
	.networkRecv 	= NULL,
	.next			= NULL,
};

static int serverInit(void)
{
	int value;
	int ret;
	struct sockaddr_in laddr;

	server.fd = socket(AF_INET,SOCK_STREAM,0);
	if(server.fd <0)
	{
		fprintf(stderr,"socket_init socket error %s",strerror(errno));
		return -1;
	}

	value =1;
	ret = setsockopt(server.fd,SOL_SOCKET,SO_REUSEADDR,&value,sizeof(value));
	if(ret <0)
	{
		fprintf(stderr,"socket_init setsockopt addr error %s",strerror(errno));
		return -2;
	}

	value =1;
	ret = setsockopt(server.fd,SOL_SOCKET,SO_REUSEPORT,&value,sizeof(value));
	if(ret <0)
	{
		fprintf(stderr,"socket_init setsockopt port error %s",strerror(errno));
		return -3;
	}

	laddr.sin_family = AF_INET;
	laddr.sin_port = htons(atoi(WEATHER_PORT));
	inet_pton(AF_INET,"0.0.0.0",&laddr.sin_addr.s_addr);
	ret = bind(server.fd,(void *)&laddr,sizeof(laddr));
	if(ret <0)
	{
		fprintf(stderr,"socket_init bind error %s",strerror(errno));
		return -4;
	}

	ret = listen(server.fd,200);
	if(ret <0)
	{
		fprintf(stderr,"socket_init listen error %s",strerror(errno));
		return -5;
	}	

	return 0;

}

static int serverExit(void)
{
	close(server.fd);

	return 0;
}

int serverNetWorkInit(void)
{
	int ret;
	
	ret = registerNetWork(&server);
	return ret;
}


